package org.bing.zion.core;

import java.nio.ByteBuffer;

public class ProtocolFilterChain extends ProtocolFilterAdapter {
	private MessageDispatcher dispatcher;
	private ProtocolFilterWrapper first;
	private ProtocolFilterWrapper last;

	public void setMessageDispatcher(MessageDispatcher dispatcher) {
		this.dispatcher = dispatcher;
	}

	public MessageDispatcher getMessageDispatcher() {
		if (dispatcher == null) {
			dispatcher = new SimpleDispatcher();
		}
		return dispatcher;
	}

	// TODO impl dynamic filter update, more position setting
	public void addFilter(ProtocolFilter filter) {
		if (first == null) {
			first = new ProtocolFilterWrapper(this, filter);
			last = first;
			return;
		}
		ProtocolFilterWrapper wrapper = new ProtocolFilterWrapper(this, filter);
		wrapper.setPrevWrapper(last);
		last.setNextWrapper(wrapper);
		last = wrapper;
	}

	public ProtocolFilter first() {
		if (first != null) {
			return first;
		} else {
			return new ProtocolFilterWrapper(this, new ProtocolFilterAdapter());
		}
	}

	public ProtocolFilter last() {
		if (last != null) {
			return last;
		} else {
			return new ProtocolFilterWrapper(this, new ProtocolFilterAdapter());
		}
	}

	public void dispatch(Session session, Object msg) {
		this.getMessageDispatcher().dispatch(session, msg);
	}

	public void flush(Session session, ByteBuffer buf) {
		session.flush(buf);
	}

	// NOTICE impl by subclass, ProtocolFilterWrapper
	public ProtocolFilter next() {
		throw new UnsupportedOperationException("Impl in subclass,ex: ProtocolFilterWrapper!");
	}

	public ProtocolFilter prev() {
		throw new UnsupportedOperationException("Impl in subclass,ex: ProtocolFilterWrapper!");
	}

}
